<template>
  <div>
    <div class="login-box">
      <form>
        <div class="user-box">
          <input type="text" name="" required v-model="account.username">
          <label>用户名</label>
        </div>
        <div class="user-box">
          <input type="password" name="" required v-model="account.password">
          <label>密码</label>
        </div>
        <div class="to-center">
          <el-select v-model="value" placeholder="Select"
                    style="background-color: darkslategrey; color: #fff;">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <a @click="doLogin" class="a-distance">
          登录
          <span></span>
        </a>
        <a @click="doregist" style="cursor: pointer">
          注册
          <span></span>
        </a>
      </form>
    </div>
  </div>
</template>


<script setup lang="ts">
import {reactive, ref} from 'vue'
import {useLoginStore} from "@/stores";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import {check_user} from "@/api/api";

const router = useRouter()
const value = ref('')
const account = reactive({
  username: "",
  password: "",
})
const options = [
  {
    label: '管理员',
    value: 'admin',
  },
  {
    label: '经理',
    value: 'manager',
  },
  {
    label: '用户',
    value: 'user',
  }
]

const loginStore = useLoginStore()

async function doLogin() {
  try {
    let key = await check_user(account.username,account.password,value.value)
    if (key && key.data.role) {
      loginStore.login(key.data.role);
    } else {
      // 如果没有获取到 role 或 key 为空，可以进行错误处理
      console.error('Failed to login or role not found.');
    }
    await router.replace("/home/basic")
    ElMessage({
      type: 'info',
      message: `登录成功`,
    });
  }catch (error) {
    ElMessage({
      type: 'info',
      message: `没有该账号`,
    });
  }
}

function doregist() {
  router.replace("/regist")
  ElMessage({
    type: 'info',
    message: `欢迎来到注册界面`,
  });
}
</script>



<style scoped>
@import "@/css/loginBox.css";
</style>